/**
 * Copyright (c) 2020 libinbin000
 * SFrame is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 *     http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

import {DB} from "../core/db/DB";
import {ModelBase} from "./model/ModelBase";

export class PlayerDataBase{
    private uid:number = 0;

    public load(uid:number, callback:Function = null){
        this.uid = uid;

        DB.query("SELECT payload FROM storage WHERE uid =" + uid, (error, results, fields)=>{
            if(!results || results.length == 0 || !results[0].payload){
                //数据库里没有数据
                this.save(()=>{
                    callback && callback();
                })
            }else{
                //数据库里有数据
                let storage = JSON.parse(results[0].payload);
                for(let key in this){
                    if(this[key] instanceof ModelBase){
                        let model:ModelBase = <any>this[key];
                        let storageKey = model.getStorageKey();
                        if(storage[storageKey]){
                            model.setData(storage[storageKey]);
                        }
                    }
                }

                callback && callback();
            }
        });
    }

    public save(callback:Function = null){
        let data:any = {};
        for(let key in this){
            if(this[key] instanceof ModelBase){
                let model:ModelBase = <any>this[key];
                let storageKey = model.getStorageKey();
                data[storageKey] = model.getData();
            }
        }
        
        let json = JSON.stringify(data);
        DB.query(`REPLACE INTO  storage(uid, payload)VALUES(${this.uid}, '${json}');`, (error, results, fields)=>{
            if(error){
                console.log("存档错误")
            }
            callback && callback();
        });
    }
}